package vip.xiaonuo.modular.file.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.qiniu.storage.model.DefaultPutRet;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.modular.file.util.QiniuUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 七牛云工具类
 * @author linfen
 * @since 2020-04-8
 */
@Slf4j
@Api(tags = "七牛云文件服务")
@RestController
public class QiNiuController {
 
    @Autowired
    private QiniuUtil qiniuUtil;
 
    /**
     * 七牛云文件上传
     *
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    public ResponseData upload(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseData.error("上传文件不能为空");
        }
        try {
            InputStream fileInputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = qiniuUtil.upload(fileInputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file.getSize());
            //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
            map.put("url", "/" + uploadInfo.key);
//            map.put("url", "/linfen/qiniu/file/" + uploadInfo.key);//七牛云公开下载地址
            log.info("文件：" + JSON.toJSONString(map));
            return ResponseData.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("上传失败");
        }
    }
 
    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @PostMapping("/private/file/{filename}")
    public ResponseData privateDownload(@PathVariable("filename") String filename) {
        if (filename.isEmpty()) {
            return null;
        }
        try {
            String privateFile = qiniuUtil.getPrivateFile(filename);
            log.info("文件下载地址：" + privateFile);
           return  ResponseData.success(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.success();
    }
 
    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @GetMapping("/file/{filename}")
    public ResponseData download(@PathVariable("filename") String filename) {
        if (filename.isEmpty()) {
            return null;
        }
        //http://qyt23bmbm.hn-bkt.clouddn.com/98fa074135a44286b721a71901058d5f-20210902210433.jpeg
        try {
            String privateFile = qiniuUtil.getFile(filename);
            log.info("文件下载地址：" + privateFile);
            return  ResponseData.success(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ResponseData.success();
    }
 
    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */
    @PostMapping("/delete/file/{filename}")
    public ResponseData deleteFile(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return ResponseData.error("未知文件");
        }
 
        try {
            boolean result = qiniuUtil.delete(filename);
            if (result)
                return ResponseData.success("文件删除成功");
            else
                return ResponseData.error("文件删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("文件删除失败");
        }
    }
}